package com.jnevision.login;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.jnevision.config.ErrorCode;
import com.jnevision.dept.model.Dept;
import com.jnevision.dept.service.DeptServiceImpl;
import com.jnevision.user.model.User;
import com.jnevision.user.service.UserServiceImpl;
import com.jnevision.userdept.model.UserDept;
import com.jnevision.userdept.service.UserDeptServiceImpl;
import com.jnevision.userrole.model.UserRole;
import com.jnevision.userrole.service.UserRoleServiceImpl;
import com.jnevision.util.JsonMapper;

@RestController
public class LoginController extends ApiController {
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private UserRoleServiceImpl userRoleServiceImpl;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserDeptServiceImpl userDeptServiceImpl;
    @Autowired
    private DeptServiceImpl deptServiceImpl;
    private static final String TOKEN_PREFIX = "Bearer:";

    /**
     * 用户登录
     * 
     * @param phone
     * @param password
     * 
     * @return -1 登录失败，0登录成功； 成功后返回token，前台需要永久的存储token，需要拿token来获取用户信息
     */
    @GetMapping("/login")
    public R<String> login(String phone, String password, HttpSession session) {
        User user = this.userServiceImpl.getOne(new QueryWrapper<User>().eq("phone", phone).eq("password",
            DigestUtils.md5DigestAsHex(password.getBytes())));
        if (Objects.isNull(user)) {
            return this.failed("用户名密码错误");
        }

        user.setPassword("");
        UserRole one = this.userRoleServiceImpl.getOne(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
        if (null != one) {

            user.setRoleId(one.getRoleId());
        }
        UserDept one2 = this.userDeptServiceImpl.getOne(new QueryWrapper<UserDept>().eq("user_id", user.getId()));
        if (null != one2) {
            user.setDeptId(one2.getDeptId());
        }
        Dept byId = this.deptServiceImpl.getById(user.getDeptId());
        if (null != byId) {

            user.setDeptName(byId.getName());
        }

        String token = session.getId();
        this.redisTemplate.opsForValue().set(TOKEN_PREFIX + token, JsonMapper.nonDefaultMapper().toJson(user)); // 登录成功后存储token，有效期为6个小时
        this.redisTemplate.expire(TOKEN_PREFIX + token, 6, TimeUnit.HOURS);

        return this.success(TOKEN_PREFIX + token);
    }

    /**
     * 拿token获取登录的用户信息
     * 
     * @param token
     * @return code为-1时登录超时，0成功
     */
    @GetMapping("/login/user")
    public R<User> getLoginUser(@RequestHeader(value = "token") String token) {
        User user = JsonMapper.nonDefaultMapper().fromJson(this.redisTemplate.boundValueOps(token).get(), User.class);
        if (!Objects.isNull(user)) {
            return this.success(user);
        }

        return R.failed(ErrorCode.NO_LOGIN);
    }

    /**
     * 退出
     * 
     * @param token
     * @return
     */
    @GetMapping("/logout")
    public R<Boolean> logout(@RequestHeader(value = "token") String token) {
        try {
            return this.success(redisTemplate.delete(token));
        } catch (Exception e) {
            e.printStackTrace();
            return this.failed("退出失败，用户或已退出");
        }
    }

}
